package com.hpq.websocket;

import cn.hutool.core.net.url.UrlBuilder;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;

import java.util.Optional;

/**
 *  websocket握手处理
 */
public class WebSocketHandShakeHandler extends ChannelInboundHandlerAdapter {
    public void channelRead(final ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest req = (FullHttpRequest)msg;
            UrlBuilder builder =  UrlBuilder.ofHttp(req.uri());
            // 获取token参数
            Optional<String> token = Optional.ofNullable(builder.getQuery()).map(k->k.get("token")).map(CharSequence::toString);
            //token不为空，保存token
            token.ifPresent(t -> NettyUtil.setAttr(ctx.channel(), NettyUtil.TOKEN, t));
            // 获取请求路径
            req.setUri(builder.getPath().toString());
        }
           ctx.fireChannelRead(msg);
    }
}
